//
//  AssociatedObjectViewController.m
//
//  Created by 周成龙
//

#import "AssociatedObjectViewController.h"

#import <objc/runtime.h>

static NSString *const kAssociatedKey = @"associatedKey";
@interface AssociatedObjectViewController ()<UIAlertViewDelegate>

@end

@implementation AssociatedObjectViewController
#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // 可以给某对象关联许多其他对象，这些对象通过“键”来区分。存储对象值的时候，可以指明‘存储策略’，用以维护相应的‘内存管理语义’
    /**
     关联类型:
     OBJC_ASSOCIATION_ASSIGN                assign
     OBJC_ASSOCIATION_RETAIN_NONATOMIC      nonatomic,retain
     OBJC_ASSOCIATION_COPY_NONATOMIC        nonatomic,copy
     OBJC_ASSOCIATION_RETAIN                retain
     OBJC_ASSOCIATION_COPY                  copy
     */
    
    // 管理关联对象
    // 1. 以给定的键和策略为某对象设置关联对象值
    // void objc_setAssociatedObject(<#id object#>, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)
    
    // 2. 根据给定的键从某对象中获取相应的关联对象值
    // id objc_getAssociatedObject(<#id object#>, <#const void *key#>)
    
    // 3. 移除指定对象的全部关联对象
    // void objc_removeAssociatedObjects(<#id object#>)
    
    // 通常：在设置关联对象值时，通常使用静态全局变量做键
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Question" message:@"what are you wangt to do?" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"continue", nil];
    
    void (^block)(NSInteger) = ^(NSInteger buttonIndex){
        if (buttonIndex == 0) {
            [self doCancel];
        }else {
            [self doContinue];
        }
    };
    
    objc_setAssociatedObject(alert, (__bridge const void *)(kAssociatedKey), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    [alert show];
}

- (void)doCancel {
    NSLog(@"doCancel");
}

- (void)doContinue {
    NSLog(@"doContinue");
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    void (^block)(NSInteger) = objc_getAssociatedObject(alertView, (__bridge const void *)(kAssociatedKey));
    block(buttonIndex);
}

- (void)dealloc {
    NSLog(@"AssociatedObjectViewController 释放");
}

@end
